﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UCWebpart.Admin
{
    public partial class ResourcesUserControl : System.Web.UI.UserControl
    {
        string uName;
        string uType1;
        string uType3;


        UserInfo userInfo;
        int uLevel = 0;//最高级别权限，判断是否为3级管理员
        List<MTR_Admin> AdminInfoList;

        protected void Page_Load(object sender, EventArgs e)
        {
            Label2.Text = "";
            if (Session["userName"] == null)
            {
                Response.Redirect("../Login.aspx", false);
                return;
            }
            uName = Session["userName"].ToString();
            uType1 = Session["orgType1"].ToString();
            uType3 = Session["orgType3"].ToString();

            userInfo = (UserInfo)Session["userInfo"];
            AdminInfoList = userInfo.AdminInfoList;

            foreach (MTR_Admin ma in AdminInfoList)
            {
                uLevel = uLevel > Convert.ToInt32(ma.adminLevel) ? uLevel : Convert.ToInt32(ma.adminLevel);//
            }
            if (uLevel == 1)
            {
                res.Attributes.Add("style", "display:none");//隐藏
            }
            if (uLevel >= 2)
            {
                res.Attributes["style"] = "display:''";//显示
            }
            if (!IsPostBack)
            {
                bindResources();
                string getTopOne = string.Format(@"
                SELECT top 1 MTR_bas_Meetingroom.mtrId FROM MTR_bas_Meetingroom (nolock) where mtrDelete=1 and 
                3 in (select distinct adminLevel from MTR_bas_Admin(nolock) where adminName='{0}' and Available=1)
                union
                select MTR_bas_Meetingroom.mtrId from MTR_bas_Admin with(nolock) join MTR_bas_Meetingroom with(nolock) 
                on MTR_bas_Admin.[VenueType]=MTR_bas_Meetingroom.[type]
                where adminName='{0}' and MTR_bas_Admin.Available='1' and MTR_bas_Meetingroom.mtrDelete='1'", Session["userName"].ToString());
                string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;
                DataTable dt = Worker.GetDataSet(getTopOne, conn).Tables[0];
                if (dt.Rows[0][0] != null)
                {
                    CheckBoxListBind(Convert.ToInt32(dt.Rows[0][0].ToString()));
                }
            }
        }
       
        protected void ResSelectedAdd(int mtrId, int resId)
        {
            using (var mtr_Add = new meetingroomManagementEntities())
            {
                MTR_bas_MeetingroomResources mr = new MTR_bas_MeetingroomResources();
                mr.mtrId = mtrId;
                mr.resId = resId;
                mtr_Add.MTR_bas_MeetingroomResources.Add(mr);
                mtr_Add.SaveChanges();
            }
        }
        protected void ResDeleteAll(int mtrId) {
            using (var mtr_delAll = new meetingroomManagementEntities()) {
                var cls = (from rs in mtr_delAll.MTR_bas_MeetingroomResources
                           where rs.mtrId == mtrId
                           select new
                           {
                               resId = rs.resId
                           }).ToList();

                foreach(var c in cls){
                    var mtrRes = (from rs1 in mtr_delAll.MTR_bas_MeetingroomResources
                               where rs1.mtrId==mtrId && rs1.resId== c.resId
                                  select rs1).SingleOrDefault<MTR_bas_MeetingroomResources>();

                    mtr_delAll.MTR_bas_MeetingroomResources.Remove(mtrRes);
                    mtr_delAll.SaveChanges();
                }
            }
        }

        protected void Button1_Click1(object sender, EventArgs e)
        {
            try
            {
                int mtrId = Convert.ToInt32(DropDownList1.SelectedValue);
                //删除所有此会议室关联的资源
                ResDeleteAll(mtrId);

                for (int i = 0; i < Recourses.Items.Count; i++)
                {
                    if (Recourses.Items[i].Selected == true)
                    {
                        //存入一行到数据库
                        ResSelectedAdd(mtrId, Convert.ToInt32(Recourses.Items[i].Value));
                    }
                }
                Label2.Text = "<script>alert('场地资源维护成功！'); </script>";
                CheckBoxListBind(mtrId);
            }
            catch(Exception ex){
                Label2.Text = "<script>alert('" + ex.Message + "'); </script>";
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //清空checkboxlist
            for (int i = 0; i < Recourses.Items.Count; i++)
            {
                Recourses.Items[i].Selected = false;
            }
            int mtrId =Convert.ToInt32( DropDownList1.SelectedValue);
            CheckBoxListBind(mtrId);
        }

        protected void bindResources()
        {
            string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;
            string strGetRes = "SELECT [resName], [resId] FROM [MTR_bas_Resources] where del = 1";
            Recourses.DataSource = Worker.GetDataSet(strGetRes, conn);
            Recourses.DataTextField = "resName";
            Recourses.DataValueField = "resId";
            Recourses.DataBind();
        }

        protected void CheckBoxListBind(int mtrId ) {
            using (var mtrEntity = new meetingroomManagementEntities())
            {
                MTR_bas_MeetingroomResources mtrres = new MTR_bas_MeetingroomResources();
                var cls = (from r in mtrEntity.MTR_bas_Resources
                           join rs in mtrEntity.MTR_bas_MeetingroomResources
                               on r.resId equals rs.resId
                           where
                               rs.mtrId == mtrId && r.del
                           select new
                           {
                               resName = r.resName,
                               resId = r.resId
                           }).ToList();
                foreach (var kk in cls)
                {
                    for (int i = 0; i < Recourses.Items.Count; i++)
                    {
                        if (kk.resId == Convert.ToInt32(Recourses.Items[i].Value))
                        {
                            Recourses.Items[i].Selected = true;
                        }
                    }
                }
            }
        }

        protected void TextBox2_TextChanged(object sender, EventArgs e)
        {

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                string newRes = resName.Text;
                using (var addRes = new meetingroomManagementEntities())
                {
                    MTR_bas_Resources r = new MTR_bas_Resources();
                    r.resName = newRes;
                    r.del = true;

                    addRes.MTR_bas_Resources.Add(r);
                    addRes.SaveChanges();
                    Label2.Text = "<script>alert('资源添加成功！'); </script>";
                    //Response.Write();
                    Response.Redirect("ResourcesManage.aspx", false);
                }
            }
            catch(Exception ex){
                Label2.Text = "<script>alert('" + ex.Message + "'); </script>";
                //Response.Write("<script>alert('"+ ex.Message+"'); </script>");
            }
        }

        protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            Response.Redirect("ResourcesManage.aspx", false);
        }
    }
}